<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">

      <!-- 所属分类：级联下拉列表 -->
      <el-form-item label="课程类别">
        <el-cascader v-model="subjectSelectIds" placeholder="试试搜索：java" :options="subjectList" :props="props"
          filterable>
        </el-cascader>
      </el-form-item>

      <!-- 标题 -->
      <el-form-item>
        <el-input v-model="searchObj.title" placeholder="课程标题" />
      </el-form-item>
      <!-- 讲师 -->
      <el-form-item>
        <el-select v-model="searchObj.teacherId" placeholder="请选择讲师">
          <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
        </el-select>
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
      <el-button type="danger" @click="batchDelete()">批量删除</el-button>
    </el-form>

    <!-- 表格 -->
    <el-table :data="courseList" border stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="#" width="40">
        <template slot-scope="scope">
          {{ (currPage - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="封面" width="150" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.cover" :src="scope.row.cover" alt="scope.row.title" width="100%">
        </template>
      </el-table-column>
      <el-table-column label="课程信息">
        <template slot-scope="scope">
          <a href="">{{ scope.row.title }}</a>
          <p>
            分类：{{ scope.row.subjectParentTitle }} > {{ scope.row.subjectTitle }}
          </p>
          <p>
            课时：{{ scope.row.lessonNum }} /
            浏览：{{ scope.row.viewCount }} /
            付费学员：{{ scope.row.buyCount }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="讲师" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.teacherName }}
        </template>
      </el-table-column>
      <el-table-column label="价格(元)" width="100" align="center">
        <template slot-scope="scope">
          <!-- {{ typeof '0' }}  {{ typeof 0 }} {{ '0' == 0 }} -->
          <!-- {{ typeof scope.row.price }}
              {{ typeof Number(scope.row.price) }}
              {{ typeof Number(scope.row.price).toFixed(2) }} -->

          <el-tag v-if="Number(scope.row.price) === 0" type="success">免费</el-tag>

          <!-- 前端解决保留两位小数的问题 -->
          <!-- <el-tag v-else>{{ Number(scope.row.price).toFixed(2) }}</el-tag> -->

          <!-- 后端解决保留两位小数的问题，前端不用处理 -->
          <el-tag v-else>{{ scope.row.price }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="课程状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 'Draft' ? 'warning' : 'success'">{{ scope.row.status === 'Draft' ? '未发布' : '已发布' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtCreate.substr(0, 10) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <router-link :to="'/course/info/'+scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit">修改</el-button>
          </router-link>
          <router-link :to="'/course/chapter/'+scope.row.id">
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑大纲</el-button>
          </router-link>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeCourse(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination background style="padding: 30px;" layout="prev, pager, next, jumper, sizes, ->, total" :page-sizes="[5, 10, 20, 50]"
      :total="totalCount" :page-size="limit" :page-count="totalPage" :current-page="currPage" @current-change="changePage"
      @size-change="changeSize">
    </el-pagination>
  </div>
</template>

<script>
  import {
    getCourseById,
    getPageList,
    removeById,
    batchRemove
  } from '@/api/course'
  import {
    list
  } from '@/api/teacher'
  import {
    getNestedTreeList
  } from '@/api/subject'

  export default {
    data() {
      return {
        // 查询条件对象
        searchObj: {},
        // 课程分类级联选择的id数组
        subjectSelectIds: [],
        // 课程分类列表
        subjectList: [],
        props: {
          value: 'id',
          label: 'title',
          children: 'children'
        },
        // 讲师列表
        teacherList: [],
        // 课程列表
        courseList: [],
        listLoading: true,
        totalCount: 0, // 总记录数
        totalPage: 0, // 总页数
        currPage: 1, // 当前页码
        limit: 5, // 每页条数
        multipleSelection: [] // 存放选中的数据id
      }
    },
    created() {
      this.fetchData()
      this.getTeacherList()
      this.getSubjectList()
    },
    methods: {
      fetchData() {
        getPageList(this.currPage, this.limit, this.searchObj).then(response => {
          this.courseList = response.data.list
          this.totalCount = response.data.totalCount
          this.limit = response.data.pageSize
          this.totalPage = response.data.totalPage
          this.listLoading = false
        })
      },
      // 改变分页是触发
      changePage(page) {
        this.currPage = page
        this.fetchData()
      },
      changeSize(size) {
        this.limit = size
        this.fetchData()
      },

      // 选择时触发
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 单个删除
      removeCourse(id) {
        // 询问是否删除
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return removeById(id)
        }).then(response => {
          // 刷新页面
          this.fetchData()
          // 弹出成功提示
          this.$message({
            message: response.message,
            type: 'success'
          })
        }).catch((err) => {
          console.log(err)
          if (err === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          }
        })
      },
      // 批量删除
      batchDelete() {
        // 判断是否已选择数据
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'warning',
            message: '请先选择要删除的数据'
          })
        } else {
          // 询问是否删除
          this.$confirm('此操作将永久删除这些数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            this.multipleSelection.forEach(item => {
              ids.push(item.id)
            })
            return batchRemove(ids)
          }).then(response => {
            // 刷新页面
            this.fetchData()
            // 弹出成功提示
            this.$message({
              message: response.message,
              type: 'success'
            })
          }).catch((err) => {
            console.log(err)
            if (err === 'cancel') {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            }
          })
        }
      },
      // 重置条件，查询全部
      resetData() {
        this.searchObj = {}
        this.fetchData()
        this.subjectSelectIds = []
      },
      // 查询讲师列表
      getTeacherList() {
        list().then(response => {
          this.teacherList = response.data
        })
      },

      // 查询课程分类
      getSubjectList() {
        getNestedTreeList().then(response => {
          this.subjectList = response.data
        })
      }
    }
  }
</script>

<style>
</style>
